import { Button, Progress } from "antd"
import React, {  useRef, useState } from "react"
import nickJson from "./nicks"
import { useMemoizedFn } from "ahooks";


function App(): JSX.Element {

  const timeRef = useRef<any>(null);
  // 生成昵称列表
  const [nickList, setNickList] = useState<string[]>([]);
  const [percent, setPercent] = useState(0);
  const [step, setStep] = useState(0);
  const [tips] = useState([
    "取名必须结合天时地利人和",
    "当前黄道吉时，一切必然顺利",
    "让老夫先算上一挂",
    "金克木，木克土，土克水，水克火，火克金",
    "金生水，水生木，木生火，火生土，土生金",
    "五行相生相克，五行相克相生",
    "老夫已有决断，无需多言",
  ]);
  // 生成昵称
  const handleClick = useMemoizedFn(() => {
    if(timeRef.current) clearInterval(timeRef.current);
    setStep(0);
    setPercent(0);
    timeRef.current = setInterval(() => handleProgress(), 500);
  })


  const handleProgress = useMemoizedFn(() => {
    const pcent = Math.min(100,percent+ Math.floor(Math.random() * 10));
    const step = pcent/16 >> 0;
    setStep(step);
    setPercent(pcent);
    if(pcent >= 100) {
      const newNick = pickNick();
      setNickList([...nickList, newNick]);
      if(timeRef.current) clearInterval(timeRef.current);
    }
  })

  const pickNick = () => {
    const nickIndex = Math.floor(Math.random() * nickJson.length);
    return nickJson[nickIndex];
  }

  // 重置
  const handleReset = () => {
    if(timeRef.current) clearInterval(timeRef.current);
    setStep(0);
    setPercent(0);
    setNickList([]);
  }

  return (
    <main className="p-5">
      <header>
        <h1 className="flex justify-center items-center text-2xl">昵称生成器</h1>
      </header>
      <section className="py-5">
        <div className="flex justify-center items-center gap-1">
          <Button type="primary" onClick={() => handleClick()}>生成昵称</Button>
          <Button type="primary" onClick={handleReset}>清空</Button>
        </div>
        <div>
          <Progress percent={percent} showInfo={false} />
          <div>
            {tips[step]}
          </div>
        </div>
      </section>
      <h3>历史记录：</h3>
      <ul className="h-[200px] overflow-x-hidden">
       {
          nickList.map((nick) => {
            return <li className="py-2 border-b-2 border-gray-300" key={nick}>{nick}</li>
          })
       }
      </ul>
    </main>
  )
}

export default App
